package com.example.task.ui;

import static java.lang.Integer.parseInt;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.example.task.R;
import com.example.task.bean.Comment;
import com.example.task.bean.Lecture;
import com.example.task.bean.User;
import com.example.task.delegate.SimpleDelegateAdapter;
import com.example.task.handler.AddNumHandler;
import com.example.task.http.Threads.AllActThreads;
import com.example.task.http.Threads.EvaluateThread;
import com.example.task.http.Threads.GetEvaluateThread;
import com.example.task.http.Threads.JudgeUserIsSignByActivityIDThread;
import com.example.task.http.Threads.SignUpBackNumByActIdThread;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import okhttp3.FormBody;

public class CommentActivity extends AppCompatActivity {

//    @BindView(R.id.recyclerView)

//    @BindView(R.id.refreshLayout)


    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //变量声明
        //变量声明
//        SwitchIconView mSwitchIconView;
//        final int[] i = {1};
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comments2);

        SimpleDelegateAdapter<Comment> mNewsAdapter;
        SmartRefreshLayout refreshLayout = findViewById(R.id.refreshLayout);
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(CommentActivity.this);
        recyclerView.setLayoutManager(layoutManager);

        final Intent[] intent = {getIntent()};
        Bundle bundle = intent[0].getExtras();
        Lecture lecture = (Lecture) bundle.getSerializable("Lecture");
        User user = (User) bundle.getSerializable("User");

        Button setcomment = findViewById(R.id.setcomment);
        FormBody.Builder builder2 = new FormBody.Builder();
        builder2.add("iduser",Integer.toString(user.getIduser()));
        builder2.add("actID",lecture.getActivityId());
        JudgeUserIsSignByActivityIDThread thread2 = new JudgeUserIsSignByActivityIDThread(builder2);
        thread2.start();
        try {
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread2.value);
        if(Objects.equals(thread2.value, "error")){
            setcomment.setText("未参加，不可评论");
        }
        LinearLayout layout = findViewById(R.id.layout);
        setcomment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(setcomment.getText().toString().equals("评论")){
                    System.out.println("点击了评论");
                    setcomment.setVisibility(View.GONE);
                    System.out.println("???");
                    layout.setVisibility(View.VISIBLE);
                }
            }
        });



        FormBody.Builder builder = new FormBody.Builder();
        builder.add("actID", lecture.getActivityId());
        List<Comment> commentList = getComment(builder);
        TextView title = findViewById(R.id.title);
        title.setText("活动评论 （"+commentList.size()+")");
        ImageButton button = findViewById(R.id.IV2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mNewsAdapter = new SimpleDelegateAdapter<Comment>(R.layout.activity_comments_item, new LinearLayoutHelper(),commentList) {

            @Override
            protected void bindData(@NonNull RecyclerViewHolder holder, int position, Comment comment) {
                if (comment != null) {
                    String date = comment.getDate();
                    holder.text(R.id.name, comment.getName());
                    holder.text(R.id.time, date.substring(0,4)+"/"+date.substring(5,7)+"/"
                            +date.substring(8,10)+" "+date.substring(11,13)+":"+date.substring(14,16));
                    holder.text(R.id.text,comment.getData());
                }
            }
        };
        recyclerView.setAdapter(mNewsAdapter);

        refreshLayout.setOnRefreshListener(refreshLayout1 -> refreshLayout1.getLayout().postDelayed(() -> {
            List<Comment> commentList1 = getComment(builder);
            mNewsAdapter.refresh(commentList1);
            refreshLayout1.finishRefresh();
        }, 1000));
        //上拉加载
        EditText editText = findViewById(R.id.you_comment);
        editText.setText("");
        Button send = findViewById(R.id.send);
        AddNumHandler handler = new AddNumHandler(title, send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(editText.getText().toString().equals("")){
                    Toast.makeText(CommentActivity.this, "不可发送空白评论", Toast.LENGTH_LONG).show();
                }else{
                    FormBody.Builder builder = new FormBody.Builder();
                    builder.add("username", user.getUsername());
                    builder.add("activityID", lecture.getActivityId());
                    builder.add("data", editText.getText().toString());
                    EvaluateThread thread = new EvaluateThread(builder);
                    thread.start();
                    try {
                        thread.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(thread.value);
                    List<Comment> commentList1 = getComment(builder);
                    Toast.makeText(CommentActivity.this, "评价完成", Toast.LENGTH_LONG).show();
                    new Thread(() -> {
                        Message message=handler.obtainMessage();
                        message.what=3;
                        message.obj="活动评论 （"+commentList1.size()+"）";
                        handler.sendMessage(message);//发送信息
                    }).start();

                    mNewsAdapter.refresh(commentList1);
                    editText.setText("");

                }

            }
        });

//        //上拉加载
//        refreshLayout.setOnLoadMoreListener(refreshLayout -> refreshLayout.getLayout().postDelayed(() -> {
//            mNewsAdapter.loadMore(DemoDataProvider.getDemoNewInfos());
//            refreshLayout.finishLoadMore();
//        }, 1000));
        refreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
    }

    private List<Comment> getComment(FormBody.Builder builder){
        List<Comment> commentList = new ArrayList<>();
        GetEvaluateThread thread = new GetEvaluateThread(builder);
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("comment"+thread.value);
        JsonArray obj = new Gson().fromJson(thread.value, JsonArray.class);
        for(JsonElement jsonElement : obj){
            String userID = jsonElement.getAsJsonObject().get("userID").toString().replace("\"","");
            String activityID = jsonElement.getAsJsonObject().get("activityID").toString().replace("\"","");
            String evaluateID = jsonElement.getAsJsonObject().get("evaluateID").toString().replace("\"","");
            String data = jsonElement.getAsJsonObject().get("data").toString().replace("\"","");
            String date = jsonElement.getAsJsonObject().get("date").toString().replace("\"","");
            String name = jsonElement.getAsJsonObject().get("name").toString().replace("\"","");
            Comment comment = new Comment(userID, activityID, evaluateID, data, date, name);
            commentList.add(comment);
        }
        Collections.reverse(commentList);
        return commentList;
    }
    @Override
    public void finish() {
        super.finish();
        //关闭activity动画显示
        this.overridePendingTransition(0, R.anim.activity_close);
    }

}